﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WFNetLib;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using WFNetLib.GSMModem;
using WFNetLib.Forms;
using WFNetLib.Net;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Collections;

namespace MMDownload
{
    public class ReaderThread
    {
        public SerialPort Com;
        public Thread ReaderThreadIns=null;
        public static event strEventHandler AddLogEvent;//事件声明
        public static event intEventHandler FinishEvent;//事件声明
#if DEBUG
        CommunicationDebugForm CommunicationDebugForm;
#endif


        GsmModem gsmModem;
        public string PortName;
        public int ComIndex;
        void OnAddLog(string strLog)
        {
            if (AddLogEvent != null)
            {  
                AddLogEvent(this,new strEventArgs(strLog));
            }
        }
        void OnFinishEvent(int n)
        {
            if (FinishEvent != null)
            {
                FinishEvent(this, new intEventArgs(n));
            }
        }     
        public ReaderThread(SerialPort _Com,int index)
        {
            Com = _Com;
            
#if DEBUG
            CommunicationDebugForm = new CommunicationDebugForm();
            //CommunicationDebugForm.IsClose = true;
            CommunicationDebugForm.Show();
            //CommunicationDebugForm.Hide();
            CommunicationDebugForm.Text = Com.PortName + "数据检测";
            gsmModem = new GsmModem(Com,CommunicationDebugForm);
#else
            gsmModem = new GsmModem(Com);
#endif

            ComIndex = index;
            gsmModem.dIP[0] = 10;
            gsmModem.dIP[1] = 0;
            gsmModem.dIP[2] = 0;
            gsmModem.dIP[3] = 172;
            gsmModem.dPort = 80;       
            gsmModem.AddLog += new strEventHandler(gsmModem_AddLog);
            
        }

        void gsmModem_AddLog(object sender, strEventArgs e)
        {
            OnAddLog(e.strArg);
        }
        public void ReaderThreadStart()
        {
            ReaderThreadIns = new Thread(new ThreadStart(ReaderProc));
            ReaderThreadIns.Name = "签到" + Com.PortName;
            PortName = Com.PortName;
            ReaderThreadIns.Start();
            OnAddLog("签到开始");
        }
        private void ReaderProc()
        {
             //try
             {
                while (true)
                {
                    try
                    {
                        Com.Open();
                        //Com.RtsEnable = true;
                    }
                    catch
                    {
                        OnAddLog("串口无法打开,请终止软件");
                        OnFinishEvent((int)FinishType.Unkown);
                        break;
                    }
                    OnAddLog("开始初始化");
                    if (!gsmModem.InitGSMModem())
                    {
                        break;
                    }
                    OnAddLog("初始化成功");
                    OnAddLog("开始拨号");
                    if (!gsmModem.InitPPPConnect())
                    {
                        break;
                    }
                    OnAddLog("拨号成功");
                    string uri;
                    string tx;
                    object o;
                    string str="";                    
                    string post;
                    //string signCodeSystem = "";                    
                    string registerTime;
                    string pwd;
                    string phone;
                    string asptoken;
                    string goodsid;
                    string paymode;
                    Http http=null;
                    WebHeaderCollection httpHeader = new WebHeaderCollection();
                    httpHeader[HttpRequestHeader.UserAgent] = "Java/1.6.0_16";
                    httpHeader["X-Online-Host"] = "uas.mmarket.com:8090";
                    httpHeader["x-up-calling-line-id"] = "";
                    httpHeader["ua"] = "Nokia6300";
                    httpHeader["useragent"] = "Nokia6300";
                    httpHeader[HttpRequestHeader.ContentType] = "Application";
                    httpHeader[HttpRequestHeader.Accept] = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
                    httpHeader["Proxy-Connection"] = "keep-alive";
                    httpHeader[HttpRequestHeader.ContentLength] = "74";
                    httpHeader[HttpRequestHeader.Host] = "uas.mmarket.com:8090";
                    CookieCollection cookies = new CookieCollection();                     
                    bool bok = false;
                    while (true)
                    {
                        uri = "http://uas.mmarket.com:8090/register";
                        tx = HttpStatic.HttpHeaderToStr("POST", uri, httpHeader, cookies);
                        post = "<req><imsi>00000000000</imsi><apid>3</apid><channel_id></channel_id></req>";
                        tx = tx + post;
                        Debug.WriteLine(tx);
                        CommunicationDebugForm.ExternShowTx(tx);
                        registerTime = DateTime.Now.ToString("MMddyyyyHHmmss");
                        if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
                        {
                            OnAddLog("获得tcp数据失败!");
                            OnFinishEvent((int)FinishType.Unkown);
                            break;
                        }
                        o = gsmModem.TCPData.oTCPDatas;
                        if (o == null)
                            break;
                        http = (Http)o;
                        if (http.ContentDatas.Count == 0)
                            break;
                        str = HttpStatic.ContentToStr(http);
                        CommunicationDebugForm.ExternShowRx(http.strHttpHeader);
                        CommunicationDebugForm.ExternShowRx(str);
                        Hashtable ht = WFNetLib.Net.HttpStatic.HttpGetContentList(str);
                        str = (string)ht["resp"];
                        ht.Clear();
                        ht = WFNetLib.Net.HttpStatic.HttpGetContentList(str);
                        byte[] unKown = new byte[30];
                        unKown[0]=0xfe;
                        unKown[1]=0xfd;
                        unKown[2]=0xfc;
                        unKown[3]=0xfb;
                        unKown[4]=0x00;
                        unKown[5]=0x00;
                        unKown[6]=0x00;
                        unKown[7]=0xd5;
                        unKown[8]=0x00;
                        unKown[9]=0x01;
                        unKown[10]=0x00;
                        unKown[11]=0x01;
                        unKown[12]=0x00;
                        unKown[13]=0x00;
                        unKown[14]=0x00;
                        unKown[15]=0x0b;
                        unKown[16]=0x00;
                        unKown[17]=0x00;
                        unKown[18]=0x00;
                        unKown[19]=0x00;
                        unKown[20]=0x00;
                        unKown[21]=0x01;
                        unKown[22]=0x00;
                        unKown[23]=0x01;
                        unKown[24]=0x00;
                        unKown[25]=0x02;
                        unKown[26]=0x00;
                        unKown[27]=0x00;
                        unKown[28]=0x00;
                        unKown[29]=0xb7;
                        uri = "http://uas.mmarket.com:8090/supermail";
                        httpHeader["x-up-calling-line-id"] = (string)ht["msisdn"];
                        phone = (string)ht["msisdn"];
                        pwd = (string)ht["pwd"];
                        post = "<req>"+
                                WFNetLib.Net.HttpStatic.HttpMakeContent(ht,"msisdn")+
                                WFNetLib.Net.HttpStatic.HttpMakeContent(ht, "pwd") +
                                "<ua>Nokia6300</ua><ver>MM1.5.3.003.1_KJAVA_JT</ver><comm_ver>2</comm_ver><application>MM</application><channel_id></channel_id>"+
                                "</req>";
                        httpHeader[HttpRequestHeader.ContentLength] = (30 + post.Length).ToString();
                        tx = HttpStatic.HttpHeaderToStr("POST", uri, httpHeader, cookies);
                        List<byte> ltx=new List<byte>(Encoding.ASCII.GetBytes(tx));
                        ltx.AddRange(unKown);
                        ltx.AddRange(Encoding.ASCII.GetBytes(post));                        
                        
                        if (!gsmModem.TCPRead(ltx))
                        {
                            OnAddLog("获得tcp数据失败!");
                            OnFinishEvent((int)FinishType.Unkown);
                            break;
                        }
                        o = gsmModem.TCPData.oTCPDatas;
                        if (o == null)
                            break;
                        http = (Http)o;
                        if (http.ContentDatas.Count == 0)
                            break;
                        CommunicationDebugForm.ExternShowRx(http.ContentDatas);
                        int ContentIndex;
                        for (ContentIndex = 0; ContentIndex < http.ContentDatas.Count; ContentIndex++)
                        {
                            if (http.ContentDatas[ContentIndex] != '<')
                                continue;
                            if(http.ContentDatas[ContentIndex+1]=='r'&&
                                http.ContentDatas[ContentIndex+2]=='e'&&
                                http.ContentDatas[ContentIndex+3]=='s'&&
                                http.ContentDatas[ContentIndex+4]=='p'&&
                                http.ContentDatas[ContentIndex+5]=='>')
                                break;
                        }
                        if(ContentIndex==http.ContentDatas.Count)
                            break;
                        str = Encoding.ASCII.GetString(http.ContentDatas.ToArray(), ContentIndex, http.ContentDatas.Count - ContentIndex);
                        CommunicationDebugForm.ExternShowTx(str);
                        Hashtable ht1 = WFNetLib.Net.HttpStatic.HttpGetContentList(str);
                        str = (string)ht1["resp"];
                        ht1.Clear();
                        ht1 = WFNetLib.Net.HttpStatic.HttpGetContentList(str);
                        httpHeader.Clear();
                        httpHeader["X-Online-Host"] = "odp.mmarket.com";
                        httpHeader["ua"] = "Nokia6300";
                        asptoken = (string)ht1["token"];
                        httpHeader["asp-token"] = (string)ht1["token"];
                        httpHeader["appname"] = "MM1.5.3.003.1_KJAVA_JT";
                        httpHeader["Accept"] = "*/*";
                        httpHeader["User-Agent"] = "Nokia6300";
                        httpHeader["phone"] = (string)ht["msisdn"];
                        httpHeader["Proxy-Connection"] = "keep-alive";
                        httpHeader["Accept-Language"] = "zh-cn,en";
                        httpHeader["themeid"] = "1";
                        httpHeader["Accept-Charset"] = "utf-8, *;q=0.1";
                        httpHeader["Host"] = "odp.mmarket.com";
                        uri = "http://odp.mmarket.com/t.do?requestid=all_search_index&keyword=%E5%A4%A7%E5%AD%A6%E6%AF%95%E4%B8%9A%E4%BB%8E%E6%96%B0%E5%BC%80%E5%A7%8B";
                        tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
                        CommunicationDebugForm.ExternShowTx(tx);
                        if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
                        {
                            OnAddLog("获得tcp数据失败!");
                            OnFinishEvent((int)FinishType.Unkown);
                            break;
                        }
                        o = gsmModem.TCPData.oTCPDatas;
                        if (o == null)
                            break;
                        http = (Http)o;
                        if (http.ContentDatas.Count == 0)
                            break;
                        str = HttpStatic.ContentToStr(http);
                        CommunicationDebugForm.ExternShowRx(http.strHttpHeader);
                        CommunicationDebugForm.ExternShowRx(str);
                        int nCom=0,nCom1=0;
                        while(true)
                        {
                            nCom = str.IndexOf("AspListExt href=\"", nCom);
                            if (nCom == -1)
                            {                                
                                break;
                            }
                            nCom1 = str.IndexOf("</AspListExt>", nCom);
                            if (nCom1 == -1)
                            {
                                break;
                            }
                            if (str.IndexOf("黑龙江海旭科技有限公司", nCom, nCom1 - nCom) == -1)
                            {
                                nCom = nCom1 + "</AspListExt>".Length;
                            }
                            else
                                break;                            
                        }
                        if (nCom == -1 || nCom1==-1)
                        {
                            OnAddLog("未找到链接");
                            break;
                        }
                        nCom = nCom + "AspListExt href=\"".Length;
                        string strLink = str.Substring(nCom, str.IndexOf('"', nCom) - nCom);
                        strLink = strLink.Replace("大学毕业从新开始", "%E5%A4%A7%E5%AD%A6%E6%AF%95%E4%B8%9A%E4%BB%8E%E6%96%B0%E5%BC%80%E5%A7%8B");
                        if (http.Cookies.Count != 0)
                        {
                            foreach (Cookie c in http.Cookies)
                            {
                                if (cookies[c.Name] != null)
                                    cookies[c.Name].Value = c.Value;
                                else
                                    cookies.Add(c);
                            }
                        }                        
                        uri = "http://odp.mmarket.com" + strLink;
                        tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
                        CommunicationDebugForm.ExternShowTx(tx);
                        if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
                        {
                            OnAddLog("获得tcp数据失败!");
                            OnFinishEvent((int)FinishType.Unkown);
                            break;
                        }
                        o = gsmModem.TCPData.oTCPDatas;
                        if (o == null)
                            break;
                        http = (Http)o;
                        if (http.ContentDatas.Count == 0)
                            break;
                        str = HttpStatic.ContentToStr(http);
                        CommunicationDebugForm.ExternShowRx(http.strHttpHeader);
                        CommunicationDebugForm.ExternShowRx(str);
                        if (str.IndexOf("黑龙江海旭科技有限公司") == -1 || str.IndexOf("大学毕业从新开始") == -1)
                        {
                            OnAddLog("获得链接错误!");
                            break;
                        }
                        nCom = 0;
                        nCom = str.IndexOf("请确定是否购买。' url='");
                        if (nCom == -1)
                        {
                            OnAddLog("未找到下载链接");
                            break;
                        }
                        nCom = nCom + "请确定是否购买。' url='".Length;
                        strLink = str.Substring(nCom, str.IndexOf('\'', nCom) - nCom);
                        if (http.Cookies.Count != 0)
                        {
                            foreach (Cookie c in http.Cookies)
                            {
                                if (cookies[c.Name] != null)
                                    cookies[c.Name].Value = c.Value;
                                else
                                    cookies.Add(c);
                            }
                        }
                        nCom = strLink.IndexOf("goodsid=");
                        if (nCom == -1)
                        {
                            OnAddLog("获得关键数据goodsid失败!");
                            OnFinishEvent((int)FinishType.Unkown);
                            break;
                        }
                        nCom = nCom + "goodsid=".Length;
                        goodsid = strLink.Substring(nCom, strLink.IndexOf('&', nCom) - nCom);


                        nCom = strLink.IndexOf("payMode=");
                        if (nCom == -1)
                        {
                            OnAddLog("获得关键数据payMode失败!");
                            OnFinishEvent((int)FinishType.Unkown);
                            break;
                        }
                        nCom = nCom + "payMode=".Length;
                        paymode = strLink.Substring(nCom, strLink.IndexOf('&', nCom) - nCom);
                        
                        cookies = new CookieCollection();
                        httpHeader["x_up_calling_line_id"] = (string)ht["msisdn"];
                        string mmcode = GsmModem.MMCode(phone, asptoken, registerTime, goodsid, paymode, pwd);
                        string base64 = Convert.ToBase64String(Encoding.Default.GetBytes(registerTime + pwd));
                        httpHeader["MM_VERIFICATION_CODE"] = mmcode+base64;
                        uri = strLink;//.Replace("=dynamic&channelId=&adId=","=");
                        tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
                        CommunicationDebugForm.ExternShowTx(tx);
                        if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
                        {
                            OnAddLog("获得tcp数据失败!");
                            OnFinishEvent((int)FinishType.Unkown);
                            break;
                        }
                        o = gsmModem.TCPData.oTCPDatas;
                        if (o == null)
                            break;
                        http = (Http)o;
                        if (http.ContentDatas.Count == 0)
                            break;
                        str = HttpStatic.ContentToStr(http);
                        CommunicationDebugForm.ExternShowRx(http.strHttpHeader);
                        CommunicationDebugForm.ExternShowRx(str);
                        break;
                    }
                }
                if (!gsmModem.pppClose())
                {
                    OnAddLog("ppp关闭失败");
                }
                else
                {
                    OnAddLog("ppp关闭成功");
                }
                OnAddLog("<未知退出>");
                OnFinishEvent((int)FinishType.Unkown);
                Com.Close();
             }
//              catch (System.Exception ex)
//              {
//                  if (!gsmModem.pppClose())
//                  {
//                      OnAddLog("ppp关闭失败");
//                  }
//                  else
//                  {
//                      OnAddLog("ppp关闭成功");
//                  }
//                  OnAddLog("<未知退出>" + ex.Message);
//                  OnFinishEvent((int)FinishType.Unkown);
//                  Com.Close();
//              }            
        }        
    }
    public enum FinishType
    {
        Finish=0,
        DoAgain=1,
        Unkown=2
    }
}
